package com.sixth.docker.service.impl;

import com.alibaba.nacos.shaded.org.checkerframework.checker.units.qual.A;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sixth.core.entity.Registration;
import com.sixth.core.vo.R;
import com.sixth.docker.mapper.RegistrationMapper;
import com.sixth.docker.service.RegistrationService;
import com.sixth.docker.service.SchedulingService;
import com.sixth.docker.vo.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import java.util.List;
import java.util.Random;

/**
 * @program: sixth-hospital-parent
 * @description:
 * @author: 赵庆龙
 * @create: 2024-08-16 15:43
 **/
@Service
public class RegistrationServiceImpl implements RegistrationService {
    @Autowired
    private RegistrationMapper registrationMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private SchedulingService schedulingService;

    @Override
    public R<Registration> insert(Registration registration) {
        registration.setCreateTime(new Date());
        int i = registrationMapper.insert(registration);
        if (i > 0) {
            // 如果挂号成功，使用 Redis 原子操作获取并递增号码数
            String key = "current_number:" + registration.getDeptId();
            int currentNumber = redisTemplate.opsForValue().increment(key).intValue();
            registration.setRegistrationNumber(currentNumber);
            return R.ok(registration);
        } else {
            return R.error("挂号失败");
        }
    }

    @Override
    public R<Registration> updateByReservation(Registration registration) {
        // 使用 Redis 原子操作获取当前号码数并递增
        String key = "current_number:" + registration.getDeptId();
        int currentNumber = redisTemplate.opsForValue().increment(key).intValue();

        // 将递增后的号码数赋值给 registration 对象的 registrationNumber 字段
        registration.setRegistrationNumber(currentNumber);

        // 执行更新操作
        int result = registrationMapper.updateById(registration);
        if (result > 0) {
            return R.ok(registration);
        } else {
            return R.error("更新失败");
        }
    }


    //修改状态
    @Override
    public R <Registration> updateStatus(@RequestBody Registration registration) {
        if (registrationMapper.updateById(registration) > 0) {
            return R.ok(registration);
        } else {
            return R.error("修改失败");
        }
    }

    @Override
    public R<IPage<Registration>> selectByPage(RegistrationVo registrationVo) {
        IPage<Registration> page = new Page<>(registrationVo.getPageNum(), registrationVo.getPageSize());
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        if (registrationVo.getUserId() != null && registrationVo.getUserId().intValue() != 1) {
            wrapper.eq("user_id", registrationVo.getUserId());
        }

        if (registrationVo.getDeptId() != null) {
            wrapper.eq("dept_id", registrationVo.getDeptId());
        }
        if (StringUtils.hasText(registrationVo.getPatientName())) {
            wrapper.like("patient_name", registrationVo.getPatientName());
        }
        if (StringUtils.hasText(registrationVo.getQueryDate())) {
            wrapper.eq("visit_date", registrationVo.getQueryDate());
        }
        if (StringUtils.hasText(registrationVo.getRegStatus())) {
            wrapper.eq("registration_status", registrationVo.getRegStatus());
        }
        if (StringUtils.hasText(registrationVo.getSchedulingType())) {
            wrapper.eq("scheduling_type", registrationVo.getSchedulingType());
        }
        if (StringUtils.hasText(registrationVo.getSubsectionType())) {
            wrapper.eq("subsection_type", registrationVo.getSubsectionType());
        }
        // 过滤掉 registration_number 为 null 或空字符串的记录
        wrapper.isNotNull("registration_number");

        wrapper.orderByDesc("create_time");
        IPage<Registration> registrationIPage = registrationMapper.selectPage(page, wrapper);
        return R.ok(registrationIPage);
    }

    /**
     * 待就诊列表
     * @param registrationStatusVo
     * @return
     */
    @Override
    public R<List<Registration>> queryToBeSeen(RegistrationStatusVo registrationStatusVo) {
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.eq("scheduling_type", registrationStatusVo.getSchedulingType());// 添加新的过滤条件
        wrapper.eq("user_id", registrationStatusVo.getUserId());
        wrapper.eq("registration_status", "1");
        List<Registration> registrations = registrationMapper.selectList(wrapper);

        return R.ok(registrations);
    }

    /**
     * 就诊中列表
     * @param registrationStatusVo
     * @return
     */
    @Override
    public R<List<Registration>> queryVisiting(RegistrationStatusVo registrationStatusVo) {
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.eq("scheduling_type", registrationStatusVo.getSchedulingType());// 添加新的过滤条件
        wrapper.eq("user_id", registrationStatusVo.getUserId());
        wrapper.eq("registration_status", "2");
        List<Registration> registrations = registrationMapper.selectList(wrapper);

        return R.ok(registrations);
    }

    /**
     * 就诊已完成列表
     * @param registrationStatusVo
     * @return
     */
    @Override
    public R<List<Registration>> queryVisitCompleted(RegistrationStatusVo registrationStatusVo) {
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.eq("scheduling_type", registrationStatusVo.getSchedulingType());// 添加新的过滤条件
        wrapper.eq("user_id", registrationStatusVo.getUserId());
        wrapper.eq("registration_status", "3");
        List<Registration> registrations = registrationMapper.selectList(wrapper);

        return R.ok(registrations);
    }
//修改状态
@Override
public R<Registration> updateByStatus(String registrationId) {
    // 获取今天的日期，格式为 YYYY-MM-DD
    String today = LocalDate.now().toString();

    UpdateWrapper<Registration> updateWrapper = new UpdateWrapper<>();
    updateWrapper.eq("registration_id", registrationId)
            .set("registration_status", "2")
            .set("visit_date", today);  // 设置 visit_date 为今天的日期

    if (registrationMapper.update(null, updateWrapper) > 0) {
        return R.ok(registrationMapper.selectById(registrationId));
    } else {
        return R.error("修改失败");
    }
}

    @Override
    public R<IPage<Registration>> selectByPageApp(RegistrationListStatusAppVo registrationListStatusAppVo) {
        // 创建分页对象
        IPage<Registration> page = new Page<>(registrationListStatusAppVo.getPage(), registrationListStatusAppVo.getPageSize());

        // 创建查询条件包装器
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();

        // 添加查询条件：根据 patientId 查询
        wrapper.eq("patient_id", registrationListStatusAppVo.getPatientId());

        // 添加查询条件：当 orderState 为 0 时不加状态条件，查询所有记录；否则按状态查询
        if (StringUtils.hasText(registrationListStatusAppVo.getOrderState()) && !"0".equals(registrationListStatusAppVo.getOrderState())) {
            wrapper.eq("registration_status", registrationListStatusAppVo.getOrderState());
        }


        // 执行分页查询
        IPage<Registration> registrationIPage = registrationMapper.selectPage(page, wrapper);

        // 返回查询结果
        return R.ok(registrationIPage);
    }




    @Override
    public R<Registration> addAppRegistration(RegistrationAppVo registrationAppVo) {
        System.out.println(registrationAppVo);
        // 创建新的 Registration 对象
        Registration registration = new Registration();
        // 新的 CareOrder 插入逻辑与原来相同
        String prefix = "GH";
        long timestamp = System.currentTimeMillis();
        Random random = new Random();
        int randomNumber = random.nextInt(1000000);
        String registrationId = prefix + timestamp + String.format("%06d", randomNumber);
        registration.setRegistrationId(registrationId);
        // 将 RegistrationAppVo 中的数据复制到 Registration 对象
        registration.setPatientId(registrationAppVo.getPatientId());
        registration.setPatientName(registrationAppVo.getPatientName());
        registration.setDeptId(Math.toIntExact(registrationAppVo.getDeptId()));
        registration.setUserId(registrationAppVo.getUserId());
        registration.setDoctorName(registrationAppVo.getDoctorName());
        registration.setSubsectionType(registrationAppVo.getSubsectionType());
        registration.setSchedulingType("1");
        // 转换访问日期格式
        String convertedVisitDate = convertVisitDate(registrationAppVo.getVisitDate());
        registration.setVisitDate(convertedVisitDate);
        registration.setRegistrationItemId(1);
        registration.setRegistrationAmount(new BigDecimal("6.00"));
        // 设置其他必要的字段，例如创建时间、状态等
        registration.setCreateTime(new Date());
        registration.setUpdateTime(new Date());
        registration.setRegistrationStatus("0"); // 假设 1 表示有效状态
        // 保存到数据库
        int result = registrationMapper.insert(registration);
        if (result > 0) {
            return R.ok(registration);
        } else {
            return R.error("添加挂号记录失败");
        }
    }

    @Override
    public R<Registration> deleteRegistration(String registrationId) {
        registrationMapper.deleteById(registrationId);
        return R.ok();
    }

    @Override
    public R<List<Registration>> getAppointmentsBypatientId(RegistrationStatusVo registrationStatusVo) {
        QueryWrapper<Registration> wrapper = new QueryWrapper<>();
        wrapper.eq("patient_id", registrationStatusVo.getPatientId());
        wrapper.eq("user_id", registrationStatusVo.getUserId());
        wrapper.eq("registration_status", "0");
        //registration_number不为空


        List<Registration> registrations = registrationMapper.selectList(wrapper);
        return R.ok(registrations);
    }

    @Override
    public R<List<Registration>> selectReservations(ReservationsVo reservationsVo) {
        List<Registration> registration = registrationMapper.selectReservations(reservationsVo);
        return R.ok(registration);
    }


    public String convertVisitDate(String originalDate) {
        // 移除 "周" 及其后面的字符
        String dateWithoutWeekday = originalDate.split("周")[0];

        // 获取当前年份
        int currentYear = LocalDate.now().getYear();

        // 构建新的日期字符串
        String newDateStr = currentYear + "-" + dateWithoutWeekday;

        // 解析新的日期字符串为 LocalDate
        LocalDate date = LocalDate.parse(newDateStr, DateTimeFormatter.ofPattern("yyyy-MM-dd"));

        // 如果解析出的日期在过去，就加一年
        if (date.isBefore(LocalDate.now())) {
            date = date.plusYears(1);
        }

        // 格式化日期为所需的格式
        return date.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }


}
